const cloud = require('wx-server-sdk')
const find = (array, id) => {
        let target;
        array.some(item => {
            if (item._id === id) {
                target = item;
                return true;
            }
        })
        return target;
    }
    // 初始化 cloud
cloud.init({
    // API 调用都保持和云函数当前所在环境一致
    env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database();
const _ = db.command;
const $ = db.command.aggregate

exports.main = async(event, context) => {
    const response = {};
    const { OPENID } = cloud.getWXContext();
    const { total: totalScore } = await db.collection('dakaRecords') // 总得分次数
        .where({
            openid: _.eq(OPENID),
            needScore: _.eq(true)
        })
        .count();
    const { total: examCount } = await db.collection('dakaRecords') // 考试次数
        .where({
            openid: _.eq(OPENID),
            needScore: _.eq(true),
            cardType: _.eq('all')
        })
        .count();
    const { total: totalDakaCount } = await db.collection('dakaRecords')
        .where({
            openid: _.eq(OPENID)
        }).count()

    const dakaDay = await cloud.callFunction({
        name: 'getDakaRecordListsDate'
    })

    const { data: dakaList = [] } = await db.collection('dakaRecords')
        .where({
            openid: _.eq(OPENID)
        })
        .get();
    const getDakaCardsId = (dakaList) => {
        return [...new Set(dakaList.map(item => item.cardId))];
    };
    const { data: cardList } = await db.collection('cards')
        .where({
            openid: _.eq(OPENID)
        })
        .get();
    const dakaCardsId = getDakaCardsId(dakaList);
    const dakaCardsCount = dakaCardsId.length; // 打卡卡片数量
    cardTypeMap = {
        listening: 0,
        speaking: 0,
        reading: 0,
        writing: 0,
        all: 0
    };
    dakaCardsId.forEach(id => {
        const cardObj = find(cardList, id);
        if (cardObj && cardObj.cardType) {
            cardTypeMap[cardObj.cardType] += 1;
        }
    });

    const getAverageAndMax = () => {
        let maxScore = 0; // 最高得分
        let averageScore; // 平均得分
        let scoreCount = 0;
        let accScore = 0;
        const typeList = ['listening', 'speaking', 'reading', 'writing'];
        dakaList.forEach(dakaItem => {
            if (dakaItem.needScore) {
                typeList.forEach(type => {
                    const score = dakaItem[`${type}Score`] - 0;
                    if (score && !Number.isNaN(score)) {
                        accScore += score;
                        scoreCount++;
                        maxScore = Math.max(maxScore, score);
                    }
                })
            }
        })
        averageScore = (scoreCount === 0 ? 0 : accScore / scoreCount);
        return { maxScore, averageScore };
    };
    const { maxScore, averageScore } = getAverageAndMax();
    response.body = {
        totalScore,
        examCount,
        totalDakaCount,
        dakaDay: dakaDay && dakaDay.result && dakaDay.result.body,
        dakaCardsCount,
        cardUseScores: cardTypeMap,
        maxScore,
        averageScore
    };
    response.code = 200;
    return response;

}